package com.jacky.javafx.fx.controller;

import com.jacky.javafx.entities.AppUserEntity;
import com.jacky.javafx.entities.AppUserViewModel;
import com.jacky.javafx.service.AppUserService;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.Optional;
import java.util.ResourceBundle;

@Component
public class TableviewController implements Initializable {

    private static final Integer DEFAULT_PAGE_SIZE = 10;

    @Autowired
    private AppUserService appUserService;

    @FXML
    private AnchorPane anchorPane;

    @FXML
    private TableView<AppUserViewModel> tableView;

    @FXML
    private TableColumn<AppUserViewModel, Long> colId;
    @FXML
    private TableColumn<AppUserViewModel, String> colLoginName;
    @FXML
    private TableColumn<AppUserViewModel, String> colOpenId;
    @FXML
    private TableColumn<AppUserViewModel, String> colNickName;
    @FXML
    private TableColumn<AppUserViewModel, String> colGender;
    @FXML
    private TableColumn<AppUserViewModel, String> colUserGroup;
    @FXML
    private TableColumn<AppUserViewModel, String> colUserStatus;
    @FXML
    private TableColumn<AppUserViewModel, String> colRegistryTime;
    @FXML
    private TableColumn<AppUserViewModel, Void> colOperation;
    @FXML
    private Button btnFlesh;
    @FXML
    private Pagination pagination;

    @FXML
    private TextField txtId;

    @FXML
    private TextField txtName;

    @FXML
    private TextField txtTelephone;

    @FXML
    private TextField txtTotal;

    ObservableList<AppUserViewModel> list = FXCollections.observableArrayList();
    private int currentPage = 0;
    private int pageSize = 3;


    @Override
    public void initialize(URL url, ResourceBundle rb) {
        currentPage = pagination.getCurrentPageIndex();
        loadData();
        initColumnBinding();
        tableView.setItems(list);

        Callback<TableColumn<AppUserViewModel, Void>, TableCell<AppUserViewModel, Void>> cellFactory = new Callback<>() {
            @Override
            public TableCell<AppUserViewModel, Void> call(TableColumn<AppUserViewModel, Void> optColumn) {
                return new TableCell<>() {
                    private final Button btnDel = new Button("Del");
                    private final Button btnEdit = new Button("Edit");

                    {
                        btnDel.setOnAction(evt -> {
                            AppUserViewModel data = getTableView().getItems().get(getIndex());
                            System.out.println("选择的数据:" + data);
                        });
                        btnEdit.setOnAction(evt -> {
                            AppUserViewModel data = getTableView().getItems().get(getIndex());
                            System.out.println("选择的数据:" + data);
                            editUserInfo(evt, data);
                        });
                    }

                    @Override
                    protected void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setGraphic(null);
                        } else {
                            HBox btnBox = new HBox(btnEdit, btnDel);
                            setGraphic(btnBox);
                        }
                    }
                };
            }
        };
        colOperation.setCellFactory(cellFactory);

        pagination.setPageFactory(integer -> {
            System.out.println("当前页:" + integer);
            Label mLabel = new Label();
            currentPage = integer;
            loadData();
            tableView.setItems(list);
            return mLabel;

        });
    }

    private void loadData() {
        Page<AppUserViewModel> page = appUserService.findByPage(pageSize, currentPage, "");
        System.out.println("pageSize:" + pageSize + ",currentPage:" + currentPage);
        pagination.setCurrentPageIndex(currentPage);
        pagination.setPageCount(page.getTotalPages());
        list.clear();
        list.addAll(page.getContent());
    }

    private void initColumnBinding() {
        colId.setCellValueFactory(new PropertyValueFactory<>("id")); // id对应 AppUserViewModel的字段id,意思是从AppUserViewModel的id字段获取数据设置为colId列的值
        colLoginName.setCellValueFactory(new PropertyValueFactory<>("loginName"));
        colOpenId.setCellValueFactory(new PropertyValueFactory<>("openId"));
        colNickName.setCellValueFactory(new PropertyValueFactory<>("nickName"));
        colGender.setCellValueFactory(new PropertyValueFactory<>("gender"));
        colUserGroup.setCellValueFactory(new PropertyValueFactory<>("userGroup"));
        colUserStatus.setCellValueFactory(new PropertyValueFactory<>("state"));
        colRegistryTime.setCellValueFactory(new PropertyValueFactory<>("registryTime"));
    }

    @FXML
    public void reloadData() {
        loadData();
        tableView.setItems(list);
    }

    @FXML
    void evtClick(MouseEvent event) {
        int selectedIndex = tableView.getSelectionModel().getSelectedIndex();
        if (selectedIndex <= -1) return;
        Long selectId = colId.getCellData(selectedIndex);
        /*if (selectId != null) {
            Optional<AppUserEntity> appUser = appUserService.findById(selectId);
            AppUserViewModel model = new AppUserViewModel(appUser.orElse(new AppUserEntity()));

            try {
                FXMLLoader detailLoader = new FXMLLoader(getClass().getResource("/com/jacky/javafx/appUserDetail.fxml"));
                Pane detailPane = detailLoader.load();


                AppUserDetailController controller = detailLoader.getController();
                controller.model(model); // 传递数据

                Stage userDetailStage = new Stage();
                userDetailStage.setTitle("UserDetail");
                StackPane userDetailPane = new StackPane(detailPane);
                Scene userDetailScene = new Scene(userDetailPane);
                userDetailStage.setScene(userDetailScene);
                userDetailStage.show();

//                Dialog<ButtonType> dialog = new Dialog<>();
//                dialog.setDialogPane(detailPane);
//                dialog.setTitle("Detail");
//                Optional<ButtonType> clickedBtn = dialog.showAndWait();
//                if (clickedBtn.get() == ButtonType.OK) {
//
//                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/
    }

    void editUserInfo(ActionEvent event, AppUserViewModel editModel) {
        Long selectId = editModel == null ? -1 : editModel.getId();
        Optional<AppUserEntity> appUser = appUserService.findById(selectId);
        AppUserViewModel model = new AppUserViewModel(appUser.orElse(new AppUserEntity()));
        try {
            FXMLLoader detailLoader = new FXMLLoader(getClass().getResource("/com/jacky/javafx/appUserDetail.fxml"));
            Pane detailPane = detailLoader.load();


            AppUserDetailController controller = detailLoader.getController();
            controller.model(model); // 传递数据

            Stage userDetailStage = new Stage();
            userDetailStage.setTitle("UserDetail");
            StackPane userDetailPane = new StackPane(detailPane);
            Scene userDetailScene = new Scene(userDetailPane);
            userDetailStage.setScene(userDetailScene);
            userDetailStage.show();

//                Dialog<ButtonType> dialog = new Dialog<>();
//                dialog.setDialogPane(detailPane);
//                dialog.setTitle("Detail");
//                Optional<ButtonType> clickedBtn = dialog.showAndWait();
//                if (clickedBtn.get() == ButtonType.OK) {
//
//                }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
